package org.ilead.iserve.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 加密解密工具类
 * @author jill
 *
 */
public class MD5Util {
	
	private static MessageDigest md5; 
	
	public static String encode(String str) {
        String s=str;
		if(s==null){
			return "";
		}else{
			String value = null;
			MessageDigest md5 = getMD5();
			BASE64Encoder baseEncoder = new BASE64Encoder();
			try {
				value = baseEncoder.encode(md5.digest(s.getBytes("utf-8")));
			} catch (Exception ex) {
			}
			return value;
		}
	}
	
	public static String decode(String str){
		String s=str;
		if(s==null){
			return "";
		}else{
			String value = null;
			BASE64Decoder baseEncoder = new BASE64Decoder();
			try {
				byte[] byteArray = baseEncoder.decodeBuffer(str);
				value = new String(byteArray, "utf-8");
			} catch (Exception ex) {
			}
			return value;
		}
	}
	
	private static MessageDigest getMD5(){
		if(md5 == null){
			try {
				md5 = MessageDigest.getInstance("MD5");
			} catch (NoSuchAlgorithmException e) {
			}
		}
		return md5;
	}
	
	public static void main(String[] args) {
		String value = encode("aaaaa");
		System.out.println(decode(value));
	}
}
